<?php

/*
 *
 *       _/_/_/                      _/        _/_/_/_/_/
 *    _/          _/_/      _/_/    _/  _/          _/      _/_/      _/_/
 *   _/  _/_/  _/_/_/_/  _/_/_/_/  _/_/          _/      _/    _/  _/    _/
 *  _/    _/  _/        _/        _/  _/      _/        _/    _/  _/    _/
 *   _/_/_/    _/_/_/    _/_/_/  _/    _/  _/_/_/_/_/    _/_/      _/_/
 *
 *
 *  Copyright 2013-2014, Geek Zoo Studio
 *  http://www.ecmobile.cn/license.html
 *
 *  HQ China:
 *    2319 Est.Tower Van Palace
 *    No.2 Guandongdian South Street
 *    Beijing , China
 *
 *  U.S. Office:
 *    One Park Place, Elmira College, NY, 14901, USA
 *
 *  QQ Group:   329673575
 *  BBS:        bbs.ecmobile.cn
 *  Fax:        +86-10-6561-5510
 *  Mail:       info@geek-zoo.com
 */

function GZ_user_info($user_id)
{
	global $db,$ecs;

	$user_info = user_info($user_id);

	$collection_num = (int)$db->getOne("SELECT COUNT(*) FROM " .$ecs->table('collect_goods')." WHERE user_id='$user_id' ORDER BY add_time DESC");

	$await_pay = (int)$db->getOne("SELECT COUNT(*) FROM " .$ecs->table('order_info'). " WHERE user_id = '$user_id'". GZ_order_query_sql('await_pay'));
	$await_ship = (int)$db->getOne("SELECT COUNT(*) FROM " .$ecs->table('order_info'). " WHERE user_id = '$user_id'". GZ_order_query_sql('await_ship'));
	$shipped = (int)$db->getOne("SELECT COUNT(*) FROM " .$ecs->table('order_info'). " WHERE user_id = '$user_id'". GZ_order_query_sql('shipped'));
	$finished = (int)$db->getOne("SELECT COUNT(*) FROM " .$ecs->table('order_info'). " WHERE user_id = '$user_id'". GZ_order_query_sql('finished'));

	// include_once(ROOT_PATH .'includes/lib_clips.php');
	// $rank = get_rank_info();
	// print_r($rank);exit;

	/* 取得用户等级 */
	if ($user_info['user_rank'] == 0) {
		// 非特殊等级，根据等级积分计算用户等级（注意：不包括特殊等级）
		$sql = 'SELECT rank_id, rank_name FROM ' . $GLOBALS['ecs']->table('user_rank') . " WHERE special_rank = '0' AND min_points <= " . intval($user_info['rank_points']) . ' AND max_points > ' . intval($user_info['rank_points']);
	} else {
		// 特殊等级
		$sql = 'SELECT rank_id, rank_name FROM ' . $GLOBALS['ecs']->table('user_rank') . " WHERE rank_id = '$user_info[user_rank]'";
	}

	if ($row = $GLOBALS['db']->getRow($sql)) {
        $user_info['user_rank_name']=$row['rank_name'];
    } else {
        $user_info['user_rank_name']='非特殊等级';
    }

    $sql = 'SELECT * FROM ' . $GLOBALS['ecs']->table('user_rank') . " WHERE special_rank = '0' AND min_points = '0'";
    $row = $GLOBALS['db']->getRow($sql);

    if ($user_info['user_rank_name'] == $row['rank_name']) {
    	$level = 0;
    } else {
    	$level = 1;
    }

	return array(
		'id' => $user_info['user_id'],
		'name'=>$user_info['user_name'],
		'rank_name'=>$user_info['user_rank_name'],
		'rank_level' => $level,
		'collection_num' => $collection_num,
        'email' => $user_info['email'],
		"order_num" => array(
			'await_pay' => $await_pay,
			'await_ship' => $await_ship,
			'shipped' => $shipped,
			'finished' =>$finished
		)
	);
}

/**
 * 生成查询订单的sql
 * @param   string  $type   类型
 * @param   string  $alias  order表的别名（包括.例如 o.）
 * @return  string
 */
function GZ_order_query_sql($type = 'finished', $alias = '')
{
    /* 全部订单 */
    if ($type == 'all')
    {
        return '';
    }
    /* 退换货订单 */
    elseif ($type == 'back')
    {
        global $ecs;
        return ' AND `order_status`=4 OR `shipping_status`=4 ';
    }
    /* 未评论订单 */
    elseif ($type == 'wait_comment')
    {
        global $ecs;
//        return " AND `order_id` in (SELECT DISTINCT `order_id` FROM ".$ecs->table('order_goods')." WHERE `order_id` in
//                                    (SELECT `order_id` FROM ".$ecs->table('order_goods')." WHERE `user_id`={$_SESSION['user_id']} AND `shipping_status`=2) AND `isEvaluated`=0)";
        return " AND `order_id` in (SELECT DISTINCT `order_id` FROM ".$ecs->table('order_goods')." WHERE `order_id` in
                                    (SELECT `order_id` FROM ".$ecs->table('order_goods')." WHERE `user_id`={$_SESSION['user_id']} AND `shipping_status`=2))";
    }
    /* 已完成订单 */
    elseif ($type == 'finished')
    {
        return " AND {$alias}order_status " . db_create_in(array(OS_CONFIRMED, OS_SPLITED)) .
            " AND {$alias}shipping_status " . db_create_in(array(SS_SHIPPED, SS_RECEIVED)) .
            " AND {$alias}pay_status " . db_create_in(array(PS_PAYED, PS_PAYING)) . " ";
    }
    /* 待发货订单 */
    elseif ($type == 'await_ship')
    {
        return " AND   {$alias}order_status " .
            db_create_in(array(OS_CONFIRMED, OS_SPLITED, OS_SPLITING_PART)) .
            " AND   {$alias}shipping_status " .
            db_create_in(array(SS_UNSHIPPED, SS_PREPARING, SS_SHIPPED_ING)) .
            " AND ( {$alias}pay_status " . db_create_in(array(PS_PAYED)) . " OR {$alias}pay_id " . db_create_in(payment_id_list(true)) . ") ";
    }
    /* 待付款订单 */
    elseif ($type == 'await_pay')
    {
        return " AND   {$alias}order_status " . db_create_in(array(OS_CONFIRMED, OS_SPLITED, OS_UNCONFIRMED)) .
            " AND   {$alias}pay_status = '" . PS_UNPAYED . "'" .
            " AND ( {$alias}shipping_status " . db_create_in(array(SS_SHIPPED, SS_RECEIVED)) . " OR {$alias}pay_id " . db_create_in(payment_id_list(false)) . ") ";
    }
    /* 未确认订单 */
    elseif ($type == 'unconfirmed')
    {
        return " AND {$alias}order_status = '" . OS_UNCONFIRMED . "' ";
    }
    /* 未处理订单：用户可操作 */
    elseif ($type == 'unprocessed')
    {
        return " AND {$alias}order_status " . db_create_in(array(OS_UNCONFIRMED, OS_CONFIRMED)) .
            " AND {$alias}shipping_status = '" . SS_UNSHIPPED . "'" .
            " AND {$alias}pay_status = '" . PS_UNPAYED . "' ";
    }
    /* 未付款未发货订单：管理员可操作 */
    elseif ($type == 'unpay_unship')
    {
        return " AND {$alias}order_status " . db_create_in(array(OS_UNCONFIRMED, OS_CONFIRMED)) .
            " AND {$alias}shipping_status " . db_create_in(array(SS_UNSHIPPED, SS_PREPARING)) .
            " AND {$alias}pay_status = '" . PS_UNPAYED . "' ";
    }
    /* 已发货订单：不论是否付款 */
    elseif ($type == 'shipped')
    {
        return " AND {$alias}shipping_status " . db_create_in(array(SS_SHIPPED)) . " ";
    }
    else
    {
        die('函数 order_query_sql 参数错误');
    }
}
/**
 * 生成查询订单的sql
 * @param   string  $type   类型
 * @param   string  $alias  order表的别名（包括.例如 o.）
 * @return  string
 */
function _GZ_order_query_sql($type = 'finished', $alias = '')
{
    /* 已完成订单 */
    if ($type == 'finished')
    {
        return " AND {$alias}order_status " . db_create_in(array(OS_CONFIRMED, OS_SPLITED)) .
               " AND {$alias}shipping_status " . db_create_in(array(SS_SHIPPED, SS_RECEIVED)) .
               " AND {$alias}pay_status " . db_create_in(array(PS_PAYED, PS_PAYING)) . " ";
    }
    /* 待发货订单 */
    elseif ($type == 'await_ship')
    {
        return " AND   {$alias}order_status " .
                 db_create_in(array(OS_CONFIRMED, OS_SPLITED, OS_SPLITING_PART)) .
               " AND   {$alias}shipping_status " .
                 db_create_in(array(SS_UNSHIPPED, SS_PREPARING, SS_SHIPPED_ING)) .
               " AND ( {$alias}pay_status " . db_create_in(array(PS_PAYED, PS_PAYING)) . " OR {$alias}pay_id " . db_create_in(payment_id_list(true)) . ") ";
    }
    /* 待付款订单 */
    elseif ($type == 'await_pay')
    {
        return " AND   {$alias}order_status " . db_create_in(array(OS_CONFIRMED, OS_SPLITED, OS_UNCONFIRMED)) .
               " AND   {$alias}pay_status = '" . PS_UNPAYED . "'" .
               " AND ( {$alias}shipping_status " . db_create_in(array(SS_SHIPPED, SS_RECEIVED)) . " OR {$alias}pay_id " . db_create_in(payment_id_list(false)) . ") ";
    }
    /* 未确认订单 */
    elseif ($type == 'unconfirmed')
    {
        return " AND {$alias}order_status = '" . OS_UNCONFIRMED . "' ";
    }
    /* 未处理订单：用户可操作 */
    elseif ($type == 'unprocessed')
    {
        return " AND {$alias}order_status " . db_create_in(array(OS_UNCONFIRMED, OS_CONFIRMED)) .
               " AND {$alias}shipping_status = '" . SS_UNSHIPPED . "'" .
               " AND {$alias}pay_status = '" . PS_UNPAYED . "' ";
    }
    /* 未付款未发货订单：管理员可操作 */
    elseif ($type == 'unpay_unship')
    {
        return " AND {$alias}order_status " . db_create_in(array(OS_UNCONFIRMED, OS_CONFIRMED)) .
               " AND {$alias}shipping_status " . db_create_in(array(SS_UNSHIPPED, SS_PREPARING)) .
               " AND {$alias}pay_status = '" . PS_UNPAYED . "' ";
    }
    /* 已发货订单：不论是否付款 */
    elseif ($type == 'shipped')
    {
        return " AND {$alias}shipping_status " . db_create_in(array(SS_SHIPPED)) . " ";
    }
    else
    {
        die('函数 order_query_sql 参数错误');
    }
}

function gz_autoload($className) {
    $file = GZ_PATH . '/library/' . $className . '.php';
    if (file_exists($file)) {
        require_once $file;
    }
}

function getValueByDefault($value, $default) {
    if (!is_array($value)) {
        $whiteList = array();
        if (is_array($default)) {
            $whiteList = $default;
            $default = isset($default[0]) ? $default[0] : $default;
        } elseif ($value == '') {
            return $default;
        }

        if (is_string($default)) {
            $value = trim($value);
        } elseif (is_int($default)) {
            $value = intval($value);
        } elseif (is_array($default)) {
            if ($value == '') {
                return $default;
            }
            $value = (array)$value;
        } else {
            $value = floatval($value);
        }

        if ($whiteList && !in_array($value, $whiteList)) {
            $value = $default;
        }

    } else {
        foreach ($value as $key => $val) {
            $t = isset($default[$key]) ? $default[$key] : '';
            $value[$key] = getValueByDefault($value[$key], $t);
        }
        if (is_array($default)) {
            $value += $default;
        }
    }

    return $value;
}

function _GET($key = '', $default = '') {
    if (empty($key)) {
        return $_GET;
    }

    if (!isset($_GET[$key])) {
        $_GET[$key] = '';
    }
    $value = getValueByDefault($_GET[$key], $default);

    return $value;
}

function _POST($key = '', $default = '') {
    if (empty($key)) {
        return $_POST;
    }

    if (!isset($_POST[$key])) {
        $_POST[$key] = '';
    }
    $value = getValueByDefault($_POST[$key], $default);

    return $value;
}


function getImage($img)
{
    if (substr($img, 0, 4) == 'http') {
        return $img;
    }

    return dirname($GLOBALS['ecs']->url()).'/'.ltrim($img, '/');
}

function formatTime($Time)
{
	if (strlen($Time) == strlen(intval($Time))) {
		if ($Time == 0) {
			return '';
		}
		$unixTime = $Time;
	} else {
		$unixTime = strtotime($Time);
	}
	return date('Y/m/d H:i:s O', $unixTime);
}

function bjTime($Time)
{
	// $unixTime = $Time + 8*3600;
	// return date('Y/m/d H:i:s O', $unixTime);

	return local_date('Y/m/d H:i:s O', $Time);
}

function API_DATA($type, $readData)
{
	$outData = array();
	if (empty($readData)) {
		return $outData;
	}
	if (is_array($readData)) {
		$first = current($readData);
		if ($first && is_array($first)) {
			foreach ($readData as $key => $value) {
				$outData[] = API_DATA($type, $value);
			}
			return array_filter($outData);
		}
	}

	switch ($type) {
		case 'PHOTO':
            $outData = getImage($readData);
			break;
		case 'SIMPLEGOODS':
			$outData = array(
			  "goods_id" => $readData['goods_id'],
			  "name" => $readData['goods_name'],
			  "market_price" => $readData['market_price'],
			  "shop_price" => $readData['shop_price'],
			  "promote_price" => $readData['promote_price'],
			  "img" => array(
				'thumb'=>API_DATA('PHOTO', $readData['goods_img']),
				'url' => API_DATA('PHOTO', $readData['original_img']),
                'small' => API_DATA('PHOTO', $readData['goods_thumb'])
				)
			);
			break;
		case 'ADDRESS':
			$outData = array(
				"id"       => 15,
				"consignee"  => "联系人姓名",
				"email"    => "联系人email",
				"country"  => "国家id",
				"province" => "省id",
				"city"     => "城市id",
				"district" => "地区id",
				"address"  => "详细地址",
				"zipcode"  => "邮政编码",
				"tel"      => "联系电话",
				"mobile"   => "手机",
				"sign_building" => "标志建筑",
				"best_time" => "最佳送货时间"
			);
			break;
		case 'SIGNUPFIELDS':
			$outData = array(
				"id"  => 12,
			  	"name"  => "说明",
			  	"need"  => 0
			);
			break;
		case 'CONFIG':
			$outData = array(
				"shop_closed" => 0,
			  	"close_comment" => "关闭原因"
			);
			break;
		case 'CATEGORY':
			$outData = array(
				"id"    => 12,
			  	"name"  => "分类名称",
			  	"children"  => array(
			  		'id'   =>  13,
					'name' => 'ssss'
			  	)
			);
			break;
		case 'SIMPLEORDER':
			$outData = array(
			  "id" => $readData['order_id'],
			  "order_sn" => $readData['order_sn'],
			  "order_time" => $readData['order_time'],
			  "order_status" => $readData['order_status'],
			  "total_fee" => $readData['total_fee'],
			);
			break;
		case 'GOODS':
            $readData['original_img'] || $readData['original_img'] = $readData['goods_thumb'];
			$outData = array(
				"id"  =>  $readData['goods_id'],
				"cat_id" => $readData['cat_id'],
				"goods_sn" => $readData['goods_sn'],
				"goods_name" => $readData['goods_name'],
				// "goods_desc"=>$readData['goods_desc'],
                "collected" => $readData['collected'],
				"market_price" => $readData['market_price'],
				"shop_price" => price_format($readData['shop_price'], false),
				"integral" => $readData['integral'],
				"click_count" => $readData['click_count'],
				"brand_id" => $readData['brand_id'],
				// 红包
				"bonus_name" => isset($readData['bonus_name'])?$readData['bonus_name']:'',
				"bonus_money" => isset($readData['bonus_money'])?$readData['bonus_money']:0,
                // fix 没有goods_number值
				"goods_number" => is_numeric($readData['goods_number']) ? $readData['goods_number'] : 65535,
				"goods_weight" =>  $readData['goods_weight'],
				"promote_price" => $readData['promote_price_org'],
				"formated_promote_price" => price_format($readData['promote_price_org'], false),//$readData['promote_price'],
				"promote_start_date" => bjTime($readData['promote_start_date']),
				"promote_end_date"  => bjTime($readData['promote_end_date']),
				"is_shipping" => $readData['is_shipping'],
				"img" => array(
					'thumb'=>API_DATA('PHOTO', $readData['goods_img']),
					'url' => API_DATA('PHOTO', $readData['original_img']),
					'small'=>API_DATA('PHOTO', $readData['goods_thumb'])
				 ),
				"rank_prices" => array(),
				"pictures" => array(),
				"properties" => array(),
				"specification" => array()
			);
			foreach ($readData['rank_prices'] as $key => $value) {
				$outData['rank_prices'][] = array(
					"id"   =>  $key,
					"rank_name" => $value['rank_name'],
					"price" => $value['price']
				);
			}

			foreach ($readData['pictures'] as $key => $value) {
				$outData['pictures'][] = array(
					"small"=>API_DATA('PHOTO', $value['thumb_url']),
					"thumb"=>API_DATA('PHOTO', $value['thumb_url']),
					"url"=>API_DATA('PHOTO', $value['img_url'])
				);
			}

            if (!empty($readData['properties'])) {
                // $readData['properties'] = current($readData['properties']);
    			foreach ($readData['properties'] as $key => $value) {
                    // 处理分组
                    foreach ($value as $k => $v) {
                        $v['value'] = strip_tags($v['value']);
        				$outData['properties'][] = $v;
                    }
    			}
            }

			foreach ($readData['specification'] as $key => $value) {
				if (!empty($value['values'])) {
					$value['value'] = $value['values'];
					unset($value['values']);
				}
				$outData['specification'][] = $value;
			}
			break;
        default:
            break;
    }
    return $outData;
}

function ecmobile_url() {
    /* 协议 */
    $protocol = (isset($_SERVER['HTTPS']) && (strtolower($_SERVER['HTTPS']) != 'off')) ? 'https://' : 'http://';
    /* 域名或IP地址 */
    if (isset($_SERVER['HTTP_X_FORWARDED_HOST']))
    {
        $host = $_SERVER['HTTP_X_FORWARDED_HOST'];
    }
    elseif (isset($_SERVER['HTTP_HOST']))
    {
        $host = $_SERVER['HTTP_HOST'];
    }
    else
    {
        /* 端口 */
        if (isset($_SERVER['SERVER_PORT']))
        {
            $port = ':' . $_SERVER['SERVER_PORT'];

            if ((':80' == $port && 'http://' == $protocol) || (':443' == $port && 'https://' == $protocol))
            {
                $port = '';
            }
        }
        else
        {
            $port = '';
        }

        if (isset($_SERVER['SERVER_NAME']))
        {
            $host = $_SERVER['SERVER_NAME'] . $port;
        }
        elseif (isset($_SERVER['SERVER_ADDR']))
        {
            $host = $_SERVER['SERVER_ADDR'] . $port;
        }
    }

    return $protocol . $host . dirname(PHP_SELF);
}

function logResult($word='')
{
	$fp = fopen(GZ_PATH.DS.'log.txt','a');
	flock($fp, LOCK_EX) ;
	fwrite($fp, "执行日期：".strftime("%Y%m%d%H%M%S", time())."\n".$word."\n");
	flock($fp, LOCK_UN);
	fclose($fp);
}

function sign($time)
{
	return true;
}

function lang($message_id)
{
	isset($message) || require GZ_PATH.DS.'library'.DS.'message.php';
	if (isset($message[$message_id]))
    {
        return $message[$message_id];
    }
    return $message_id;
}

function abort($message_id, $data = [])
{
	out($data, $message_id, 0);
}

function out($data = [], $message_id = '', $status = 1)
{
	header('Content-Type:text/json;charset=UTF-8');
	exit(json_encode(['rs' => $status, 'message' => lang($message_id), 'data' => $data]));
}

function get_avatar($user_id)
{
	if (function_exists('session'))
	{
		if ($avatar = session('avatar'))
		{
			return $avatar;
		}
	}
	$dir = get_user_path($user_id);
	$path = EC_PATH.$dir;
	$avatar_path = $path.DS.$user_id;
	$avatar_name = $dir.DS.$user_id;
	$avatar = '';
	is_file($avatar_path.'.jpg') && $avatar = $avatar_name.'.jpg';
	is_file($avatar_path.'.png') && $avatar = $avatar_name.'.png';
	is_file($avatar_path.'.jpeg') && $avatar = $avatar_name.'.jpeg';
	if ($avatar)
	{
		return $GLOBALS['ecs']->get_domain().$avatar;
	}
	return $GLOBALS['ecs']->get_domain().'/data/avatar/default.jpg';
}

function get_user_path($uid)
{
	while (strlen($uid) < 9)
	{
		$uid = '0'.$uid;
	}
	$path_level = str_split($uid, 3);
	$path_chroot = DS.'data'.DS.implode(DS, $path_level);
	$path = EC_PATH.$path_chroot;
	if (!is_dir($path))
	{
		if (!mkdir($path, 0755, true))
		{
			exit("dir {$path} create faild!");
		}
	}
	return $path_chroot;
}

function session($name = '', $value = null, $unset = false) {
	if ($name === '') {
		return $_SESSION;
	}
	if ($name) {
		if ($unset === true) {
			if (isset($_SESSION[$name])) {
				unset($_SESSION[$name]);
				return true;
			}
		} else {
			if ($value === null) {
				return $_SESSION[$name];
			} else {
				$_SESSION[$name] = $value;
				return true;
			}
		}
	}
	return null;
}

// url解析
function api_get_url($url) {

    $out = array(
            'action' => '',
            'action_id' => 0
        );

    $site_url = dirname($GLOBALS['ecs']->url());

    if (strpos($url, $site_url) === false) {
        return $out;
    }

    if (strpos($url, '/goods.php') !== false) {
        $action = 'goods';
        $act_arr = explode('/goods.php', $url);
        if (strpos($act_arr[1], '?id=') !== false) {
            $action_id = ltrim($act_arr[1], '?id=');
        }
    } else if (strpos($url, '/category.php') !== false) {
        $action = 'category';
        $act_arr = explode('/category.php', $url);
        if (strpos($act_arr[1], '?id=') !== false) {
            $action_id = ltrim($act_arr[1], '?id=');
        }
    } else if (strpos($url, '/brand.php') !== false) {
        $action = 'brand';
        $act_arr = explode('/brand.php', $url);
        if (strpos($act_arr[1], '?id=') !== false) {
            $action_id = ltrim($act_arr[1], '?id=');
        }
    } else if (strpos($url, '/article.php') !== false) {
        $action = 'article';
        $act_arr = explode('/article.php', $url);
        if (strpos($act_arr[1], '?id=') !== false) {
            $action_id = ltrim($act_arr[1], '?id=');
        }
    } else if (strpos($url, '/group_buy.php') !== false) {
        $action = 'group_buy';
        $act_arr = explode('/group_buy.php', $url);
        if (strpos($act_arr[1], '?id=') !== false) {
            $action_id = ltrim($act_arr[1], '?id=');
        }
    } else {
        return $out;
    }

    $out['action'] = $action;
    $out['action_id'] = (int)$action_id;

    return $out;
}

function get_ads($ids)
{
    $ids = implode(',', $ids);
    ($ads = $GLOBALS['db']->getAll('SELECT ad_name,ad_link,ad_code FROM '.$GLOBALS['ecs']->table('ad')." WHERE enabled=1 AND position_id in ({$ids})")) || $ads = [];
    if ($ads)
    {
        foreach ($ads as $k => $v)
        {
            $tmp = api_get_url($v['ad_link']);
            $ads[$k]['action_id'] = $tmp['action_id'];
            $ads[$k]['action'] = $tmp['action'];
            $ads[$k]['ad_img'] = API_DATA('PHOTO', 'data/afficheimg/'.$v['ad_code']);
            unset($ads[$k]['ad_link'], $ads[$k]['ad_code']);
        }
    }
    return $ads;
}

function get_top_category()
{
    ($category = $GLOBALS['db']->getAll('SELECT cat_id,cat_name,thumb img FROM '.$GLOBALS['ecs']->table('category').' WHERE parent_id=0 AND is_show=1 AND show_in_nav=1 order by sort_order')) || $category = [];
    if ($category)
    {
        foreach ($category as $k => $v)
        {
            $category[$k]['img'] = API_DATA('PHOTO', 'data/catthumb/'.$v['img']);
        }
    }

    return $category;
}

function sms_verify($mobile, $code)
{
    $row = $GLOBALS['db']->getRow("SELECT * FROM ".$GLOBALS['ecs']->table('sms_log')." WHERE mobile='{$mobile}'");
    if ($row)
    {
        if ($code == $row['content'])
        {
            $GLOBALS['db']
                ->autoExecute($GLOBALS['ecs']->table('sms_log'), [
                    'content' => ''], $mode = 'UPDATE', "id={$row['id']}");
            return true;
        }
    }
    throw new Exception('验证码错误或过期!');
}

function send_sms_reg($mobile, $code)
{
    $reset_count = 0;
    $row = $GLOBALS['db']->getRow("SELECT * FROM ".$GLOBALS['ecs']->table('sms_log')." WHERE mobile='{$mobile}'");
    if ($row)
    {
        // 时间间隔
        if (($row['w_time']+60) > time())
        {
            throw new Exception('发送过于频繁!');
        }
        // 每天间隔
        if (($row['w_time'] + 3600*24) > time())
        {
            if ($row['count'] > 5)
            {
                throw new Exception('24小时内最多发送5次!');
            }
        }
        else
        {
            $reset_count = 1;
        }
    }
    send_sms($mobile, 32787, ['code' => $code]);
    if ($reset_count)
    {
        $row['count'] = 0;
        $GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('sms_log'), ['count' => 0], $mode = 'UPDATE', "id={$row['id']}");
    }
    if ($row)
    {
        // 更新
        $GLOBALS['db']
            ->autoExecute($GLOBALS['ecs']->table('sms_log'), [
                'content' => $code,
                'w_time' => time(),
                'count' => $row['count']], $mode = 'UPDATE', "id={$row['id']}");
    }
    else
    {
        // 写入
        $GLOBALS['db']
            ->autoExecute($GLOBALS['ecs']->table('sms_log'), [
                'mobile' => $mobile,
                'content' => $code,
                'w_time' => time(),
                'count' => 1], $mode = 'INSERT');
    }
    return true;
}

function send_sms($mobile, $tpl_id, $tpl_value)
{
    $tpl_value_str = '';
    if ($tpl_value)
    {
        $tmp = [];
        foreach ($tpl_value as $k => $v)
        {
            $tmp[] = "#{$k}#={$v}";
        }
        $tpl_value_str = urlencode(implode('&', $tmp));
    }
    $url = 'http://v.juhe.cn/sms/send';
    $args = [
        'mobile' => $mobile,
        'tpl_id' => $tpl_id,
        'tpl_value' => $tpl_value_str,
        'key' => 'c9d94c4222b3b646135aa977147cc7b3'
    ];
    $rs = http($url, $args);
    if ($rs)
    {
        $res = json_decode($rs, true);
        if ($res['error_code'])
        {
            file_put_contents(GZ_PATH.DS.'sms.log', date('Y-m-d H:i:s')."\t{$mobile}\terror_code:{$res['error_code']}\treason:{$res['reason']}\n", FILE_APPEND);
            throw new Exception('短信发送失败!');
        }
        else
        {
            return true;
        }
    }
    else
    {
        throw new Exception('网络请求失败!');
    }
}

function http($url, $args, $method = 'get')
{
    $ch = curl_init();
    $params = http_build_query($args);

    if ($method === 'get')
    {
        $p[CURLOPT_URL] = $url.'?'.$params;
    }
    if ($method === 'post')
    {
        $p[CURLOPT_URL] = $url;
        $p[CURLOPT_POSTFIELDS] = $params;
        $p[CURLOPT_POST] = 1;
    }
    $p[CURLOPT_RETURNTRANSFER] = 1;
    $p[CURLOPT_HEADER] = 0;
    curl_setopt_array($ch, $p);
    $rs = curl_exec($ch);
    curl_close($ch);
    return $rs;
}

function mobile_filter($mobile)
{
    return preg_match('/^1\d{10}$/', $mobile);
}

/*
0   未确认
1   未付款
2   未发货
3   已发货
4   已收货
5   已退货
6   已取消
7   未知
8   货到付款未发货
9   货到付款已发货
11  货到付款已付款
10  货到付款未付款
12  货到付款退款
13  货到付款未知
 */
function get_order_status($order_status, $shipping_status, $pay_status, $is_cod = 0)
{
    $status = 0;
    switch ($is_cod)
    {
        // 货到付款
        case 1:
            switch ($order_status)
            {
				case 0:
					$status = 0;
					break;
                case 1:
                    switch ($shipping_status)
                    {
                        case 0:
                            $status = 8;// 未发货
                            break;
                        case 1:
                            $status = 9;// 已发货
                            break;
                        case 2:
                            switch ($pay_status)
                            {
                                case 2:
                                    $status = 11;// 货到已付款
                                    break;
                                case 0:
                                default:
                                    $status = 10;// 货到未付款
                                    break;
                            }
                            break;
                        case 4:
                            $status = 12;// 货到付款退款
                            break;
                        default:
                            $status = 13;// 货到付款未知
                            break;

                    }
                    break;
            }
            break;
        // 预付款
        case 0:
        default:
            switch ($order_status)
            {
				case 0:
					$status = 0;
					break;
                case 1:
                    switch ($pay_status)
                    {
                        case 2:
                            switch ($shipping_status)
                            {
                                case 0:
                                    $status = 2;// 未发货
                                    break;
                                case 1:
                                    $status = 3;// 已发货
                                    break;
                                case 2:
                                    $status = 4;// 已收货
                                    break;
                                case 4:
                                    $status = 5;// 已退货
                                    break;
                            }
                            break;
                        case 0:
                        default:
                            $status = 1;// 未付款
                            break;
                    }
                    break;
                case 2:
                    $status = 6;// 已取消
                    break;
                case 4:
                    $status = 5;// 已退货
                    break;
                case 3:
                default:
                	$status = 7;// 未知
                    break;
            }
            break;
    }
    return $status;
}
